<?php
/**
 * Created by PhpStorm.
 * User: hantian
 * Date: 2017/6/18
 * Time: 下午2:08
 */

namespace App\Service;

use App\Models\Article;
use App\Models\ArticleComment;
use App\User;
use Fenos\Notifynder\Facades\Notifynder;

final class ArticleCommentService
{
    public static function createArticleComment($info)
    {


        $res = ArticleComment::create($info);

        $article = Article::where('id',$info['article_id'])->select('id','user_id')->first();
        $from_user_id = $info['user_id'];
        $to_user_id = $article['user_id'];

        return Notifynder::category('user.comment')
            ->from($from_user_id)
            ->to($to_user_id)
            ->extra(['msg'=>'对'.$article['name'].'发表了评论'])
            ->send();
    }

    public static function getArticleCommentIdByClassName($class_name, $user_id)
    {
        $condition = array();
        $condition['user_id'] = $user_id;
        $condition['name'] = $class_name;
        return ArticleComment::where($condition)->value('id');

    }

    public static function deleteArticleComment($id, $user_id)
    {
        //非作者和评论人不能删除平路
        $comment = ArticleComment::where('article_comment.id', $id)
            ->join('article', 'article.id', '=', 'article_comment.article_id')
            ->select('article_comment.*', 'article.user_id as writer_id')
            ->first();
        if ($user_id != $comment['writer_id'] && $user_id != $comment['user_id']) {
            return false;
        }
        return ArticleComment::where('id', $id)->delete();
    }

    public static function updateArticleComment($id, $info)
    {
        return ArticleComment::where('id', $id)->update($info);
    }

    public static function getArticleCommentList($article_id)
    {
        return ArticleComment::where('article_id', $article_id)
            ->join('users', 'users.id', '=', 'article_comment.user_id')
            ->select('article_comment.*', 'users.name as commetor_name')
            ->orderby('created_at', 'desc')
            ->get();
    }
}
